//
//  SFMusicViewController.m
//  Sofia
//
//  Created by Anton Chebotaev on 24/11/08.
//  Copyright 2008 IFMO. All rights reserved.
//

#import "SFMusicViewController.h"
#import "SFMusicFormatToken.h"
#import "iTunes.h"
#import "SFBasicPerformer.h"

@implementation SFMusicViewController
- (void)willBeDisplayed
{
	[silenceFormat setStringValue:[self loadTestString]];
	[avaiableTokens setStringValue:[NSString stringWithFormat:@"%@,%@,%@,%@,%@", 
									SFATitleToken, SFAAlbumToken, SFAArtistToken, SFAGenreToken, SFARatingToken]];
	[musicFormat setObjectValue:[self loadMusicFormat]];
	[musicFormat setTokenizingCharacterSet:[NSCharacterSet newlineCharacterSet]];
	[self tryMusicFormat:nil];
}
- (void)willBeClosed
{
	[self saveTestString:nil];
	[self saveMusicFormat:nil];
}

- (NSString *)title
{
	return NSLocalizedString(@"Music", @"Title of 'General' preference pane");
}

- (NSString *)identifier
{
	return @"SFMusicPane";
}

- (NSImage *)image
{
	return [NSImage imageNamed:@"iTunes.icns"];
}


- (IBAction)saveTestString:(id)sender
{
    NSString *text = [silenceFormat stringValue];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:text forKey:SFATextValue];
	NSLog(@"Test String saved to '%@'. Writing it to defaults", *text);	

	// We suppose that if we are going to save it then is is changed
	[self tryMusicFormat:nil];
}

- (NSString *)loadTestString
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *result = [defaults objectForKey:SFATextValue];
    return result;	
}

- (IBAction)saveMusicFormat:(id)sender
{
	NSLog(@"Music format saved to %@. Writing to defaults", [musicFormat stringValue]);
    NSData *musicFormatAsData = [NSKeyedArchiver archivedDataWithRootObject:[musicFormat objectValue]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:musicFormatAsData forKey:SFAMusicFormat];
	
	// We suppose that if we are going to save it then is is changed
	[self tryMusicFormat:nil];
}

- (NSArray *)loadMusicFormat
{
    NSData *musicFormatAsData = [[NSUserDefaults standardUserDefaults] objectForKey:SFAMusicFormat];
	NSArray *result = [NSKeyedUnarchiver unarchiveObjectWithData:musicFormatAsData];
    return result;
}


- (IBAction)tryMusicFormat:(id)sender {
	NSString *result = [[SFBasicPerformer sharedBasicPerformer] getFormatedMusicString];
	[sampleTest setStringValue:result];
}

@end
